package com.ymy.boot.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Ringo
 * @date 2021/6/25 15:01
 */
public class SessionExpiredHandler implements SessionInformationExpiredStrategy {
    @Override
    public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException {
        HttpServletResponse response = event.getResponse();
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        Map<String, Object> map = new HashMap<>();
        map.put("code", 401);
        map.put("message", "当前会话失效请重新登录~");

        PrintWriter writer = response.getWriter();
        try {
            writer.write(new ObjectMapper().writeValueAsString(map));
            writer.flush();
        } finally {
            if (writer != null)
                writer.close();
        }
    }
}
